package com.hanter.android.radwidget;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;

import java.util.ArrayList;
import java.util.List;

/**
 * 类名：CommonAdapter <br/>
 * 描述：GridView,ListView通用的适配器
 * 创建时间：2017/01/01 22:53
 *
 * @author hanter
 * @version 1.0
 */
public abstract class CommonAdapter<VH, T> extends BaseAdapter {

    private Context mContext;
    private List<T> mDataSet;

    public CommonAdapter(Context context) {
        this.mContext = context;
        this.mDataSet = new ArrayList<>();
    }

    public CommonAdapter(Context context, List<T> dataSet) {
        this.mContext = context;
        this.mDataSet = dataSet;
    }

    @Override
    public int getCount() {
        if (mDataSet != null) {
            return mDataSet.size();
        }
        return 0;
    }

    @Override
    public T getItem(int position) {
        if (mDataSet != null && position > 0 && position < mDataSet.size()) {
            return mDataSet.get(position);
        }
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        VH holder;

        if (convertView == null) {
            convertView = LayoutInflater.from(mContext).inflate(getItemLayoutId(position), parent, false);
            holder = onCreateViewHolder(convertView, getItemViewType(position));
            convertView.setTag(holder);
        } else {
            //noinspection unchecked
            holder = (VH) convertView.getTag();
        }

        onBindViewHolder(holder, position);

        return convertView;
    }

    @LayoutRes
    public abstract int getItemLayoutId(int position);

    public abstract VH onCreateViewHolder(View convertView, int viewType);

    public abstract void onBindViewHolder(@NonNull VH holder, int position);

}
